﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComplexNumbers
{
    class Complex
    {
        public double Real { get; set; }
        public double Imag { get; set; }

        public Complex()
        {
            Real = new double();
            Imag = new double();
        }

        public Complex(double r, double i)
        {
            this.Real = r;
            this.Imag = i;
        }

        public static Complex operator +(Complex c1, Complex c2)
        {
            return new Complex(c1.Real + c2.Real, c1.Imag + c2.Imag);
        }

        public static Complex operator -(Complex c1, Complex c2)
        {
            return new Complex(c1.Real - c2.Real, c1.Imag - c2.Imag);
        }

        public static Complex operator *(Complex c1, Complex c2)
        {
            return new Complex(c1.Real * c2.Real - c1.Imag * c2.Imag, c1.Imag * c2.Real + c1.Real * c2.Imag);
        }

        public static Complex operator /(Complex c1, Complex c2)
        {
            double real = (c1.Real * c2.Real + c1.Imag * c2.Imag) / (c2.Real * c2.Real + c2.Imag * c2.Imag);
            double imag = (c1.Imag * c2.Real - c1.Real * c2.Imag) / (c2.Real * c2.Real + c2.Imag * c2.Imag);
            return new Complex(real, imag);
        }

        public static explicit operator double(Complex complex)
        {
            if (complex.Imag == 0)
            {
                return complex.Real;
            }
            else
            {
                return double.NaN;
            }
        }

        public static implicit operator Complex(double value)
        {
            return (new Complex(value, 0));
        }

        public double this[int index]
        {
            get
            {
                if (index == 0)
                {
                    return this.Real;
                }
                else if(index == 1)
                {
                    return this.Imag;
                }
                else
                {
                    throw new IndexOutOfRangeException(string.Format("Value {0} is invalid", index));
                }
            }
            set
            {
                if (index != 1 && index != 0)
                {
                    throw new IndexOutOfRangeException(string.Format("Value {0} is invalid", index));
                }
                else if(index == 0)
                {
                    this.Real = value;
                }
                else
                {
                    this.Imag = value;
                }
            }
        }

        public override string ToString()
        {
            string sign = "";
            if (this.Imag > 0)
            {
                sign = "+";
            }
            return (this.Real.ToString() + sign + this.Imag.ToString() + "i");
        }
    }
}
